<template>
    <div class="container">
        <div class="live-detail">
            <div class="live-meta" ref="meta" id="meta">
                <div class="live-meta-content" v-if="live.state===0">
                    <div class="open-vip">
                        <div class="title">直播尚未开始</div>
                    </div>
                </div>
                <template v-else>
                    <div class="live-meta-content" v-if="canplay">
                        <div id="dplayer" class="dplayer"></div>
                    </div>
                    <div class="live-meta-content" v-else>
                        <div class="open-vip">
                            <div class="btn-area">
                                <span class="btn" @click="buyTicket">购买本场门票</span>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            <div class="live-tabs">
                <div class="tab-item" :class="{'active':tab==='hudong'}" @click="onClickTab('hudong')">互动</div>
                <div class="tab-item" :class="{'active':tab==='jieshao'}" @click="onClickTab('jieshao')">介绍</div>
                <div class="tab-item" :class="{'active':tab==='hezuo'}" @click="onClickTab('hezuo')">合作</div>
                <div class="subscribe" @click="showQrcode=true">+关注</div>
            </div>
            <div class="live-content" v-show="tab==='hudong'">
                <div class="inner" :style="{'height':contentHeight}" id="chat">
                    <div class="chat-room" id="chat-room">
                        <div class="chat-message" v-for="(msg,idx) in messages" :key="idx">
                            <div class="time">{{msg.created_at}}</div>
                            <div class="wellcome-msg" v-if="msg.type===2">{{msg.message}}</div>
                            <div class="chat-flex" v-else>
                                <img :src="msg.avatar" class="avatar" alt="">
                                <div class="flex">
                                    <div class="username">{{msg.username}}</div>
                                    <div><span class="message">{{msg.message}}</span></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="live-content" v-show="tab==='jieshao'">
                <div class="inner" :style="{'height':contentHeight}">
                    <div class="content" v-html="live.content"></div>
                </div>
            </div>
            <div class="live-content" v-show="tab==='hezuo'">
                <div class="inner" :style="{'height':contentHeight}">
                    <div class="content">商务合作内容</div>
                </div>
            </div>
            <div class="tabbar" v-show="tab==='hudong'">
                <div class="bar">
                    <div class="bar-inner">
                        <div class="comment" @click="showDialog=true">说点什么吧...</div>
                    </div>
                </div>
            </div>
        </div>
        <van-dialog
                v-model="showDialog"
                title="发表评论"
                :show-cancel-button="true"
                @confirm="handleSend"
                get-container="body"
        >
            <van-field v-model="message" type="textarea" placeholder="请输入评论内容"/>
        </van-dialog>
        <van-dialog
                v-model="showQrcode"
                :show-confirm-button="false"
                :close-on-click-overlay="true"
                style="width: 260px;"
        >
            <div class="dialog-qrcode">
                <img :src="qrcode" alt="">
                <p>长按识别上方二维码关注公众</p>
            </div>
        </van-dialog>
    </div>
</template>

<script>
    export default {
        name: "LiveDetail",
        components: {},
        data() {
            return {
                live: {},
                isLoading: true,
                qrcode: _global.qrcode,
                showDialog: false,
                showQrcode: false,
                message: null,
                tab: 'hudong',
                player: null,
                websocket: null,
                messages: [],
                show: true,
                contentHeight: 0,
                canplay: true
            }
        },
        mounted() {
            this.fetchData();
            this.contentHeight = (window.outerHeight - this.$refs.meta.clientHeight - 98) + '' + 'px';
        },
        methods: {
            fetchData() {
                this.$get('/webapi/live/get', {id: _config.id}).then(response => {
                    this.live = response.data.live;
                    this.isLoading = false;
                    this.initWebsocket();
                    this.getTicket();
                    document.title = this.live.title;
                });
            },
            showFormDialog: function () {
                this.showDialog = true;
            },
            hideFormDialog: function () {
                this.showDialog = false;
            },
            onClickTab: function (tab) {
                this.tab = tab;
            },
            initPlayer() {
                const {hls, hls_low, hls_hd, image, video_url, hls_play_url} = this.live;
                let options = {
                    container: document.getElementById('dplayer'),
                    video: {},
                    live: true,
                    lang: 'zh-cn',
                    autoplay: true,
                    volume: 1,
                };

                if (this.live.state === 1) {
                    options.live = true;
                    options.video = {
                        pic: image,
                        quality: [
                            {
                                name: '高清',
                                url: hls_hd,
                                type: 'hls',
                            },
                            {
                                name: '标清',
                                url: hls,
                                type: 'hls',
                            },
                            {
                                name: '流畅',
                                url: hls_low,
                                type: 'hls',
                            },
                        ],
                        defaultQuality: 1
                    }
                }

                if (this.live.state === 2) {
                    options.live = false;
                    options.playbackSpeed = [0.5, 0.75, 1, 1.25, 1.5, 2];
                    options.video = {
                        pic: image,
                        url: hls_play_url,
                        type: 'hls'
                    }
                }

                this.player = new DPlayer(options);
            },
            initWebsocket() {
                const {id, uid, username} = _config;
                var _this = this;
                var url = `wss://shop.gzdsx.cn/ws/vfrom=wx&tid=${id}&uid=${uid}&username=${username}`;
                var websocket = new WebSocket(url);
                websocket.onopen = function (evt) {
                    console.log("Connected to WebSocket server.");
                    _this.sendMessage(username + '进入了直播间',2);
                };

                websocket.onclose = function (evt) {
                    console.log("Disconnected");
                };

                websocket.onmessage = function (evt) {
                    //console.log('Retrieved data from server: ' + evt.data);
                    //echoMessage(JSON.parse(evt.data));
                    _this.messages.push(JSON.parse(evt.data));
                    var div = document.getElementById('chat-room');
                    div.style.marginBottom = '-100%';
                };

                websocket.onerror = function (evt, e) {
                    console.log('Error occured: ' + evt.data);
                };
                this.websocket = websocket;
                setTimeout(() => {
                    websocket.send('ping');
                }, 30000);
            },
            sendMessage(message, type) {
                const {uid, username, avatar} = _config;
                var data = {
                    uid,
                    username,
                    avatar,
                    message,
                    type,
                    tid: this.live.id
                }
                this.websocket.send(JSON.stringify(data));
            },
            handleSend() {
                if (!this.message) {
                    this.$toast.fail({message: '评论内容不能为空', className: 'w150'});
                    return false;
                }
                this.sendMessage(this.message,1);
                this.message = null;
                //this.showDialog = false;
            },
            getTicket(cb) {
                const live_id = this.live.id;
                this.$get('/webapi/live/canplay', {live_id}).then(response => {
                    this.canplay = response.data.canplay;
                    if (this.canplay) {
                        this.initPlayer();
                    }
                    if (cb) cb();
                });
            },
            buyTicket() {
                this.$get('/webapi/live/buyticket?live_id=' + this.live.id).then(response => {
                    var config = response.data.config;
                    config.timestamp = config.timeStamp;
                    config.success = (res) => {
                        this.$toast.success('付款成功');
                        this.getTicket();
                    };
                    wx.chooseWXPay(config);
                });
            },
        },
        computed: {}
    }
</script>

<style scoped>

</style>
